package org.example.service;

import com.aliyun.oss.OSS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.example.bean.Address;
import org.example.bean.Category;
import org.example.configs.OssConfig;
import org.example.dao.AddressMapper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
@Log
public class AddressServiceImpl implements AddressService{
    //配合上面的@AllArgsConstructor
    private final AddressMapper addressMapper;
    @Override
    public Address addAddress(Address address) {
        addressMapper.insert(address);
        return address;
    }

    @Override
    public List<Address> getAddressesByStatus(Integer address_status) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getAddress_status,address_status);
        //倒序
        wrapper.orderByDesc(Address::getAddress_id);
        return addressMapper.selectList(wrapper);
    }

    @Override
    public boolean updateIsDefault(Integer address_id, Integer is_default) {
        getAddressesByStatus(1).forEach(address -> {   //查找地址状态为0的地址数据
            address.setIs_default(0);  //将默认状态设为0
            addressMapper.updateById(address); //更新地址数据
        });
        Address address = addressMapper.selectById(address_id);
        address.setIs_default(is_default);
        return addressMapper.updateById(address)>0;
    }

    @Override
    public boolean updateAddressStatus(Integer address_id, Integer address_status) {
        Address address = this.addressMapper.selectById(address_id);
        if(address==null){
            throw new RuntimeException("地址不存在"+address_id);
        }
        if(address_status==0){
            address.setIs_default(0);
        }
        address.setAddress_status(address_status);
        return this.addressMapper.updateById(address)>0;
    }

    @Override
    public boolean updateAddress(Integer address_id, Address address) {
        Address address1= addressMapper.selectById(address_id);
        if(address1!=null){
            address1.setAddress_status(0);
            addressMapper.updateById(address1);
        }
        Address newaddress=addAddress(address);
        return addressMapper.updateById(newaddress)>0;//将 Address 中所有非空字段更新到数据库（如果某个字段为 null，则数据库对应字段不会被更新）。
    }

    //查找默认地址的地址信息
    @Override
    public Address getDefaultAddress(Integer is_default,Integer address_status) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getIs_default,is_default);
        wrapper.eq(Address::getAddress_status,address_status);
        return addressMapper.selectOne(wrapper);
    }
}
